//
//  TTCountTimer.m
//  ITBE
//
//  Created by ITBE on 2019/1/28.
//  Copyright © 2019年 鲍利成. All rights reserved.
//

#import "TTCountTimer.h"

@implementation TTCountTimer
-(instancetype)initWithTimerInterval:(NSTimeInterval)interval
{
    self = [super init];
    if (self) {
        timeInterval = interval;
        _status = TimerStop;
    }
    return self;
}

-(void)startTimer
{
    if (timer==nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),timeInterval*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(didReachTimeInterval)]) {
                    [self.delegate didReachTimeInterval];
                }
            });
        });
        dispatch_resume(timer); // 启动定时器
        _status = TimerStart;
    }
}

-(void)resumeTimer
{
    if (_status == TimerStart) {
        return;
    }
    
    if (timer) {
        dispatch_resume(timer);
        _status = TimerStart;
    }
}

-(void)suspendTimer
{
    if (_status == TimerSuspend) {
        return;
    }
    if (timer) {
        dispatch_suspend(timer);
        _status = TimerSuspend;
    }
}

-(void)stopTimer
{
    if (_status == TimerStop) {
        return;
    }
    
    if (timer) {
        dispatch_cancel(timer);
        timer = nil;
        _status = TimerStop;
    }
}

@end
